package org.hard.controller;


import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.IdUtil;
import com.aspose.pdf.Document;
import com.aspose.pdf.SaveFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/**
 * @author: 王林博
 * @date: 2024年04月10日 14:26
 */
@Slf4j
@RestController
public class FileConvertController {

    /**
     * pdf转work
     * @param file
     * @param response
     * @throws IOException
     */
    @PostMapping(value = "/pdf2word")
    public void upload(@RequestParam(value = "file") MultipartFile file, HttpServletResponse response) throws IOException {
        StopWatch stopWatch = new StopWatch("文件转换时间");
        stopWatch.start("准备时间");

        OutputStream outputStream = null;
        InputStream in = null;
        // 获取文件名
        String fileName = file.getOriginalFilename();
        String prefix="."+getExtensionName(fileName);
        fileName = getFileName(fileName) + ".docx";
        response.setContentType("application/octet-stream");
        try {
            File file1 = File.createTempFile(IdUtil.simpleUUID(), prefix);
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.reset();
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename="+fileName+";"+"filename*=utf-8''"+fileName);
            response.setHeader("Access-Control-Allow-Origin", "*");


            FileOutputStream os = new FileOutputStream(file1);

            Document doc = new Document(file.getInputStream());
            stopWatch.stop();
            stopWatch.start("转换时间");
            doc.save(os, SaveFormat.DocX);
            stopWatch.stop();
            stopWatch.start("写入时间");
            // 用uuid作为文件名，防止生成的临时文件重复
            // 获取输出流
            outputStream = response.getOutputStream();
            //5. 创建缓冲区

            in = new BufferedInputStream(new FileInputStream(file1));
            byte[] buffer = new byte[1024];
            int len;
            //6. 获取OutputStream对象
            //7. 将FileOutputStream流写到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端！
            while ((len=in.read(buffer))>0){
                outputStream.write(buffer,0,len);
            }
            stopWatch.stop();
            log.info(stopWatch.prettyPrint(TimeUnit.SECONDS));

            doc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(null != in){
                in.close();
            }
            if(null != outputStream){
                outputStream.close();
            }
        }

    }

    //pdf转doc
    public static void pdf2doc(String pdfPath) {
        long old = System.currentTimeMillis();
        try {
            //新建一个word文档
            String wordPath=pdfPath.substring(0,pdfPath.lastIndexOf("."))+".docx";
            FileOutputStream os = new FileOutputStream(wordPath);
            //doc是将要被转化的word文档
            Document doc = new Document(pdfPath);
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            doc.save(os, SaveFormat.DocX);
            os.close();
            //转化用时
            long now = System.currentTimeMillis();
            System.out.println("Pdf 转 Word 共耗时：" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            System.out.println("Pdf 转 Word 失败...");
            e.printStackTrace();
        }
    }

    /**
     * MultipartFile转File
     */
    public static File toFile(MultipartFile multipartFile){
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String prefix="."+getExtensionName(fileName);
        File file = null;
        try {
            // 用uuid作为文件名，防止生成的临时文件重复
            file = File.createTempFile(IdUtil.simpleUUID(), prefix);
            // MultipartFile to File
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 获取文件扩展名，不带 .
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }
    /**
     * 获取文件名，不带 扩展名
     */
    public static String getFileName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(0,dot);
            }
        }
        return filename;
    }


}
